import pygame
import time
from threading import Thread

class Joystick:
    def __init__(self):
        # 初始化pygame和手柄模块
        pygame.init()
        pygame.joystick.init()
        self.init_diff = [0.00390625, 0.00390625, 0.00390625, 0.00390625] # 定义摇杆的初始偏差，获取摇杆数据的时候会减去这个偏差
        self.axes = []
        self.buttons = []
        
    def init(self):
        try:
            self.joystick = pygame.joystick.Joystick(0)  # 0表示第一个连接的手柄
            self.joystick.init()
            
            self.continous_get_axis_data_thread = Thread(target=self.continous_get_data)
            self.continous_get_axis_data_thread.daemon = True
            self.continous_get_axis_data_thread.start()
            print(f"检测到手柄: {self.joystick.get_name()}")
            return self.joystick.get_name()
        except pygame.error:
            print("未找到手柄！")
            return None
        
    # 持续获取摇杆和和按钮数据
    def continous_get_data(self):
        while True:
            pygame.event.pump()  # 处理事件队列
            # 这里的4和2可以根据手柄的摇杆和按钮数量进行修改
            self.axes = [-(self.joystick.get_axis(i) - self.init_diff[i]) for i in range(4)]
            self.buttons = [self.joystick.get_button(i) for i in range(4)]
            time.sleep(0.05)
    # 返回摇杆数据
    def get_axis_data(self):
        return self.axes
    # 返回按钮数据
    def get_button_data(self):
        return self.buttons
    
if __name__ == '__main__':
    joystick = Joystick()
    if joystick.init() is not None:
        while True:
            print(joystick.get_button_data())
            time.sleep(0.1)